package com.apobates.forum.grief.lang;

import java.util.Map;
import java.util.Optional;

/**
 * 响应结果
 * @author xiaofanku
 * @param <T>
 */
public class ResponseResult<T> {
    private final int code;
    private final String message;
    private final T data;

    public ResponseResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    public Object getEntity(){
        return 200 == getCode()?getData():null;
    }

    /**
     * 生成指定http code的响应结果
     * @param code http status code
     * @param message 响应的消息内容
     * @return
     */
    public static ResponseResult httpResponse(int code, String message){
        return new ResponseResult<String>(code, message, null);
    }

    /**
     * 生成500的响应结果
     * @return
     */
    public static ResponseResult serverError(Exception e){
        return new ResponseResult<String>(500, e.getMessage(), null);
    }

    /**
     * 生成404的响应结果
     * @return
     */
    public static ResponseResult notFound(){
        return httpResponse(404, "查找的对象不存在");
    }

    /**
     * 对于可能存在null的响应结果
     * @param entity 响应结果
     * @param <T>
     * @return
     */
    public static <T> ResponseResult<T> optional(Optional<T> entity){
        if(!entity.isPresent()){
            return notFound();
        }
        return new ResponseResult<>(200, "ok", entity.get());
    }

    /**
     * 对于返回集合类型的结果
     * @param collection 即使不存在结果也建议使用空集合
     * @param <T>
     * @return
     */
    public static <T> ResponseResult<T> collect(T collection){
        return new ResponseResult<>(200, "ok", collection);
    }

    /**
     * 单个实例的响应结果,方法委托optional
     * @param entity
     * @param <T>
     * @return
     */
    public static <T> ResponseResult<T> ofEntity(T entity){
        return optional(Optional.ofNullable(entity));
    }

    /**
     *
     * @param entity
     * @return
     * @param <T>
     */
    public static <T> ResponseResult<T> success(T entity){
        return new ResponseResult<>(200, "ok", entity);
    }

    /**
     *
     * @param code
     * @param message
     * @return
     * @param <T>
     */
    public static <T> ResponseResult<T> fail(int code, String message){
        return new ResponseResult<>(code, message, null);
    }
    /**
     * 对于Map结构的响应结果
     * @param map
     * @return
     */
    public static ResponseResult<Map> ofMap(Map map){
        if(null == map || map.isEmpty()) {
            return notFound();
        }
        return new ResponseResult(200, "ok", map);
    }
}
